// MR页面中commits区间选择
import React, { Component } from 'react';
// import PropTypes from 'prop-types';
import queryString from 'query-string';

import { Select } from '@teamix/ui';
import track from 'utils/track';

import Overlay from './overlay';
import './index.scss';
import intl from '../../locale';

const popupProps = {
  triggerClickKeycode: [13, 32, 40], // space, enter, down-arrow
};
export default class CommitRange extends Component {
  state = {
    isPopupVisible: false,
  };

  getCommitsData = () => {
    const { commits } = this.props;
    const commitSelectData =
      commits.map((item) => {
        return {
          label: item.title,
          value: item.id,
          data: item,
        };
      }) || [];
    return commitSelectData;
  };

  handleCommitsChange = ({ newFromCommitId, newToCommitId }) => {
    this.props.updateData({
      from_commit: newFromCommitId,
      to_commit: newToCommitId,
    });

    const hashStr = window.location.hash.split('#')[1] || '';
    const hashObj = hashStr ? queryString.parse(hashStr) : {};
    const newHashObj = {
      ...hashObj,
      from_commit: newFromCommitId,
      to_commit: newToCommitId,
    };

    window.location.hash = `#${queryString.stringify(newHashObj)}`;
    this.props.getPushRecordsDiff();
    this.props.getTotalComments();
    this.props.getDrafts();
  };

  handleSelect = ({ fromIndex, toIndex }) => {
    const { commits, codeReviewDetail } = this.props;
    this.setState({
      isPopupVisible: false,
    });

    track({
      action: 'choose_push_version',
      page: 'Repo-MR-changes',
      mr_id: codeReviewDetail.id,
    });

    const newFromCommitId = commits[fromIndex].id;
    const newToCommitId = commits[toIndex].id;
    this.handleCommitsChange({
      newFromCommitId,
      newToCommitId,
    });
  };

  onVisibleChange = (visible) => {
    const { codeReviewDetail } = this.props;
    this.setState({
      isPopupVisible: visible,
    });

    if (visible) {
      track({
        action: 'check_file_commit',
        page: 'Repo-MR',
        type: '',
        control: '',
        mr_id: codeReviewDetail.id,
      });
    }
  };

  render() {
    const { from_commit, to_commit, className = '' } = this.props;
    const commitSelectData = this.getCommitsData();
    const fromIndex = commitSelectData.findIndex((item) => {
      return item.value === from_commit;
    });
    const toIndex = commitSelectData.findIndex((item) => {
      return item.value === to_commit;
    });

    const PopupContent = (
      <Overlay
        onChange={this.handleSelect}
        onClose={() => {
          this.setState({
            isPopupVisible: false,
          });
        }}
        data={commitSelectData}
        {...this.props}
      />
    );

    return (
      <div className={`commits-toggle ${className}`} id="commits-toggle">
        <Select
          value={from_commit}
          autoWidth={false}
          hasBorder={false}
          dataSource={commitSelectData}
          popupContainer={() => {
            return document.getElementById('commits-toggle');
          }}
          valueRender={() => {
            const length = Math.abs(toIndex - fromIndex) + 1;
            if (length === commitSelectData.length) {
              return (
                <span className="value-text">
                  {intl.get({
                    id: 'code-assets.components.commitSelect.SubmitAll',
                    defaultMessage: '全部提交',
                  })}
                </span>
              );
            } else {
              return (
                <span className="value-text">
                  {intl.get(
                    {
                      id: 'code-assets.components.commitSelect.LengthSubmitted',
                      defaultMessage: '{length} 个提交',
                    },
                    { length },
                  )}
                </span>
              );
            }
          }}
          className="commit-select"
          visible={this.state.isPopupVisible}
          onVisibleChange={this.onVisibleChange}
          popupProps={popupProps}
          popupContent={PopupContent}
        />
      </div>
    );
  }
}
